package xyz.bali16.module.sign.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import xyz.bali16.application.core.enums.ApiEnum;
import xyz.bali16.application.core.model.Result;
import xyz.bali16.module.sign.entity.SignAttendance;
import xyz.bali16.module.sign.entity.SignEvent;
import xyz.bali16.module.sign.model.*;
import xyz.bali16.module.sign.service.SignAttendanceService;
import xyz.bali16.module.sign.service.SignEventService;
import xyz.bali16.module.sign.service.SignPointService;

import javax.validation.Valid;

import static xyz.bali16.application.core.model.Result.*;
import static xyz.bali16.module.sign.utils.ResultUtils.errorLog;


/**
 * @author bali2 on 9/3/2023.
 * @version 1.0
 */
@RestController
@RequestMapping(BaseController.API+"sign/attendance")
@Api(tags = "签到接口")
@AllArgsConstructor

public class SignAttendanceController extends BaseController{
    public static final Logger logger = LoggerFactory.getLogger(xyz.bali16.module.sign.controller.SignAttendanceController.class);
    @Autowired
    SignAttendanceService signAttendanceService;
    @Autowired
    SignEventService signEventService;
    @Autowired
    SignPointService signPointService;
    @GetMapping
    @ApiOperation("分页条件查询签到信息")
    //@PreAuthorize("@auth.permission('plugin:attendance:query')")
    public Result<IPage<SignAttendance>> pageQuery(@Valid SignAttendancePageParam param) {
        IPage<SignAttendance> signAttendanceIPage = signAttendanceService.getPage(param);
        return success(ApiEnum.GET_SUCCESS, signAttendanceIPage);
    }
    //@GetMapping
    //////@PreAuthorize("@auth.permission('user:update')")
    //@ApiOperation(value = "查询签到列表")
    //public Result<List<SignAttendance>> getList() {
    //    LambdaQueryWrapper<SignAttendance> wrapper = Wrappers.<SignAttendance>lambdaQuery()
    //            .orderByDesc(SignAttendance::getCheckinTime);
    //    return success(ApiEnum.GET_SUCCESS, signAttendanceService.list(wrapper));
    //}
    @GetMapping("/has")
    @ApiOperation("查询是否已签到")
    @Transactional
    //@PreAuthorize("@auth.permission('plugin:attendance:query')")
    public Result<Boolean> has(@Valid SignAttendanceAddParam param) {
        try {
            return success(ApiEnum.GET_SUCCESS,signAttendanceService.has(param));
        } catch (Exception e) {
            errorLog(logger, e, "查询是否签到 '{}' 失败 {}", param.getUserId(), e.getMessage());
            return failure(ApiEnum.ADD_ERROR, "查询是否签到失败", e);
        }
    }

    @PostMapping
    ////@PreAuthorize("@auth.permission('user:add')")
    @ApiOperation("添加签到信息")
    @Transactional
    //@PreAuthorize("@auth.permission('plugin:attendance:add')")
    public Result<String> add(@RequestBody @Valid SignAttendanceAddParam param) {
        try {
            // 设置签到状态
            signAttendanceService.addSignAttendance(param);
            SignEvent signEvent = signEventService.getById(param.getEventId());
            // 设置签到积分奖励
            SignPointAddParam signPointAddParam = new SignPointAddParam();
            signPointAddParam.setPoint(signEvent.getScore());
            signPointAddParam.setUserId(param.getUserId());
            signPointService.addSignPoint(signPointAddParam);
            return response(ApiEnum.ADD_SUCCESS,"签到成功，获得签到积分: "+signEvent.getScore());
        } catch (Exception e) {
            errorLog(logger, e, "新增签到 '{}' 失败 {}", param.getUserId(), e.getMessage());
            return failure(ApiEnum.ADD_ERROR, "新增签到失败", e);
        }
    }

    @PutMapping
    @ApiOperation("修改签到")
    //@PreAuthorize("@auth.permission('plugin:attendance:update')")
    public Result<String> update(@RequestBody @Valid SignAttendanceUpdateParam param) {
        try {
            signAttendanceService.updateSignAttendance(param);
            return response(ApiEnum.UPDATE_SUCCESS);
        } catch (Exception e) {
            errorLog(logger, e, "更新签到 '{}' 信息失败 {}", param.getId(), e.getMessage());
            return failure(ApiEnum.UPDATE_ERROR, "更新签到失败", e);
        }
    }

    @DeleteMapping("/{attendanceId}")
    @ApiOperation("删除签到信息")
    @ApiImplicitParam(name = "attendanceId", value = "签到id", paramType = "path", required = true)
    //@PreAuthorize("@auth.permission('plugin:attendance:delete')")
    public Result<String> deleteAttendance(@PathVariable("attendanceId") String attendanceId) {
        try {
            signAttendanceService.delete(attendanceId);
            return response(ApiEnum.DELETE_SUCCESS);
        } catch (Exception e) {
            errorLog(logger, e, "删除签到 '{}' 失败. {}", attendanceId, e.getMessage());
            return failure(ApiEnum.DELETE_ERROR, e);
        }
    }

}
